package com.sy.olddriver.utils;

import com.alibaba.fastjson.JSON;
import com.sy.olddriver.constant.AppConstant;
import com.sy.olddriver.dto.Result;
import com.sy.olddriver.entity.User;
import com.sy.olddriver.filter.ServletHolder;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Http操作相关的工具类
 *
 * @author Administrator
 */
public class HttpUtils {
    private HttpUtils() {

    }

    /**
     * 用于构建错误的时候的返回对象
     *
     * @param errMsg 错误信息
     * @return 错误时的返回对象
     * @author Administrator
     */
    public static Result buildFailure(String errMsg) {
        Result result = new Result();
        result.setSuccess(false);
        result.setErrMsg(errMsg);
        return result;
    }


    /**
     * 将Java对象转换为一个JSON格式的数据并输出
     *
     * @param res  响应对象
     * @param data 要被转换为JSON的Java对象
     */
    public static void writeJson(HttpServletResponse res, Object data) throws IOException {
        res.setContentType(AppConstant.APPLICATION_JSON_CONTENT_TYPE);
        PrintWriter pw = res.getWriter();
        pw.print(JSON.toJSONString(data));
    }

    /**
     * 向Session对象中添加属性
     *
     * @param name  属性名
     * @param value 属性值
     */
    public static void setSessionAttribute(String name, Object value) {
        HttpServletRequest req = ServletHolder.getCurRequest();
        req.getSession().setAttribute(name, value);
    }

    /**
     * 从Session中获取属性值
     *
     * @param name 属性名
     * @return 属性值
     */
    public static Object getSessionAtrribute(String name) {
        HttpServletRequest req = ServletHolder.getCurRequest();
        return req.getSession().getAttribute(name);
    }

    /**
     * 设置Cookie
     *
     * @param name   Cookie中的属性名
     * @param value  Cookie中的属性值
     * @param expire 过期时间
     */
    public static void setCookie(String name, String value, Integer expire) {
        HttpServletResponse res = ServletHolder.getCurResponse();
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if (null != expire) {
            cookie.setMaxAge(expire);
        }
        res.addCookie(cookie);
    }

    /**
     * 根据Cookie的名称，获取Cookie的值
     *
     * @param name Cookie的名称
     * @return Cookie的值
     */
    public static String getCookie(String name) {
        HttpServletRequest req = ServletHolder.getCurRequest();
        Cookie[] cookies = req.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 删除Cookie
     *
     * @param name 要删除的Cookie的名称
     */
    public static void delCookie(String name) {
        HttpServletRequest req = ServletHolder.getCurRequest();
        HttpServletResponse res = ServletHolder.getCurResponse();
        Cookie[] cookies = req.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), name)) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    res.addCookie(cookie);
                }
            }
        }
    }


    /**
     * 获取请求的具体资源路径
     *
     * @param req 请求对象
     * @return 资源路径
     */
    public static String getMappingUri(HttpServletRequest req) {
        String servletPath = req.getServletPath();
        //  /OldDriverServer/apis/heroes/paging
        String uri = req.getRequestURI();
        //替换掉前面的项目名和组件名，得到最终的处理器映射路径
        String mappingUri = uri.replace(req.getContextPath(), "").replace(servletPath, "");
        return mappingUri;
    }


    /**
     * 用于获取当前系统中登录的用户的信息
     *
     * @return 登录的用户的具体信息
     */
    public static User getLoginUser() {
        String token = HttpUtils.getCookie(AppConstant.USER_TOKEN_COOKIE_NAME);
        String redisUserKey = AppConstant.USER_TOKEN_REDIS_PREFIX + token;
        //根据Redis中key获取登录用户信息
        User user = RedisUtils.getObj(redisUserKey);
        return user;
    }


}
